package com.dragon.logical.service.finance.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.common.util.DateNumUtils;
import com.dragon.logical.service.customer.CustomerService;
import com.dragon.logical.service.finance.ILoanService;
import com.dragon.repository.config.annotation.DataScope;
import com.dragon.repository.entity.AddPageData;
import com.dragon.repository.entity.DictsortDetail;
import com.dragon.repository.entity.Loan;
import com.dragon.repository.entity.OtherFile;
import com.dragon.repository.mapper.ExpensesMapper;
import com.dragon.repository.mapper.LoanMapper;
import com.dragon.repository.mapper.OtherFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 借款表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-07-03
 */
@Service
public class LoanServiceImpl extends ServiceImpl<LoanMapper, Loan> implements ILoanService {

    @Autowired
    LoanMapper loanMapper;
    @Autowired
    OtherFileMapper fileMapper;
    @Autowired
    CustomerService customerService;
    @Autowired
    ExpensesMapper expensesMapper;

    @Override
    @DataScope(adminField = "admin_id",deptField = "department_id", authCodeString = "loanManagement")
    public Page<Loan> loanList(Integer page, Integer limit, String search, Integer status, String startTime, String endTime) {
        Page<Loan> loanPage = new Page<>(page, limit);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        QueryWrapper<Loan> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(startTime) || StrUtil.isNotEmpty(endTime)) {
            if (StrUtil.isEmpty(endTime)) {
                endTime = DateUtil.date().toString();
            }
            if (StrUtil.isEmpty(startTime)) {
                startTime = "1999-01-01";
            }
            try {
                df.parse(startTime);
                df.parse(endTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        wrapper.lambda()
                .like(StrUtil.isNotBlank(search),Loan::getLoanName,search)
                .eq(status!=null,Loan::getStatus,status)
                .ge(StrUtil.isNotBlank(startTime), Loan::getCreateTime, startTime)
                .le(StrUtil.isNotBlank(endTime), Loan::getCreateTime, endTime);
        return loanMapper.LoanList(loanPage, wrapper);
    }

    @Override
    public AddPageData addLoan(Loan loan) {
        loan.setStatus(0);
        loan.setCreateTime(DateUtil.date());
        //自动生成编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = null;
        if (loan.getCreateTime() == null){
            date = new Date();
        } else {
            date = loan.getCreateTime();
        }
        String code = "JK-" + sdf.format(date);
        String maxCode =  loanMapper.maxRoundInoutNumber(code);
        String newCode = null;
        if (StrUtil.isEmpty(maxCode)){
            newCode = code + "001";
        }
        else {
            String getMaxCode = maxCode.substring(11, 14);
            newCode = code + DateNumUtils.getNum(getMaxCode);
        }
        loan.setNum(newCode);
        loanMapper.insert(loan);
        //添加附件
        List<OtherFile> otherFileList = loan.getOtherFileList();
        if (otherFileList != null){
            otherFileList.forEach(file -> {
                file.setCreateTime(DateUtil.date());
                file.setStreamType(9);
                file.setCorrelationId(loan.getId());
                fileMapper.insert(file);
            });
        }
        AddPageData addPageData = new AddPageData();
        addPageData.setAdminId(loan.getAdminId());
        addPageData.setCorrelationId(loan.getId());
        addPageData.setWorkflowJson(loan.getWorkflowJsonList());
        addPageData.setStreamType(9);
        addPageData.setTitle(loan.getLoanName());
        addPageData.setExempt(loan.getExempt());

        return addPageData;
    }

    @Override
    public void updateLoan(Loan loan) {
        Loan loanOne = loanMapper.selectById(loan.getId());
        if (loanOne == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        loan.setUpdateTime(DateUtil.date());
        if (loan.getOtherFileList() != null){
            loan.getOtherFileList().forEach(otherFile -> {
                fileMapper.update(otherFile,new QueryWrapper<OtherFile>().lambda()
                        .eq(OtherFile::getCorrelationId,loan.getId()).eq(OtherFile::getStreamType,9));
            });
        }
        loanMapper.updateById(loan);

    }

    @Override
    public void deleteLoan(Integer id) {
        Loan loan = loanMapper.selectById(id);
        if(loan.getStatus() != 1 ){
            customerService.deleteThorough(9,id);
            loanMapper.deleteById(id);
        }
    }

    @Override
    public Loan getLoanById(Integer id) {
        Loan loan = loanMapper.selectByLoanId(id);
        //单据类型
        String expensesName = expensesMapper.selectNameById(loan.getLoanType());
        loan.setExpensesName(expensesName);
        List<OtherFile> otherFiles = fileMapper.selectList(new QueryWrapper<OtherFile>().lambda()
                .eq(OtherFile::getCorrelationId, id).eq(OtherFile::getStreamType, 9));
        if (otherFiles != null){
            loan.setOtherFileList(otherFiles);
        } else {
            loan.setOtherFileList(new ArrayList<>());
        }
        return loan;
    }

    @Override
    public Map<String,Object> selectListStatistics(){
        return loanMapper.selectListStatistics();
    }

    @Override
    public List<DictsortDetail> loanTypePercentage(String time) {
        if (StrUtil.isBlank(time)){
            time = DateUtil.format(DateUtil.date(),"yyyy");
        }
        List<DictsortDetail> loanTypePercentage = loanMapper.loanTypePercentage(time);
        return loanTypePercentage;
    }

    @Override
    public LinkedHashMap<String, Object> loanMonthlyStatistics(String time) {
        if (StrUtil.isBlank(time)){
            time = DateUtil.format(DateUtil.date(),"yyyy");
        }
        return loanMapper.loanMonthlyStatistics(time);
    }
}
